package com.softmaker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryToFile {

    public static void main(String[] args) throws IOException {
        FileToBinary file = new FileToBinary();
        String binaryString = file.get(); // 用你实际的二进制字符串替换这里
        String outputPath = "E:\\file"; // 替换为你想保存文件的路径

        try {
            // 1. 将二进制字符串转换为字节数组
            byte[] byteArray = binaryStringToBytes(binaryString);
            File file1 = new File(outputPath + "\\test");

            // 2. 创建 FileOutputStream 对象以写入文件
            FileOutputStream fos = new FileOutputStream(file1);

            // 3. 将字节数组写入文件
            fos.write(byteArray);

            // 4. 关闭 FileOutputStream
            fos.close();

            System.out.println("File has been successfully saved at: " + outputPath);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static byte[] binaryStringToBytes(String binaryString) {
        int length = binaryString.length() / 8;
        byte[] byteArray = new byte[length];
        for (int i = 0; i < length; i++) {
            // 将每8位二进制字符串转换为对应的字节
            String byteString = binaryString.substring(i * 8, (i + 1) * 8);
            byteArray[i] = (byte) Integer.parseInt(byteString, 2);
        }
        return byteArray;
    }
}
